/**
*    This file is part of Basic Service.
*
*    Basic Service is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    Basic Service is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with Basic Service (See GPL.txt).  If not, see <http://www.gnu.org/licenses/>.
*    
* 	If needed the author is Amir Zucker and can be reached at amirzucker1@gmail.com or amirzucker.wordpress.com
*/
package com.basicservice.dto.validators;

import org.owasp.appsensor.errors.AppSensorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class SafeString {
	private static final Logger LOG = LoggerFactory.getLogger(SafeString.class);

	protected String value;
	private boolean validated;

	public SafeString() {
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getValue() {
		if (validateValue()) {
			return value;
		} else
			return null;
	}

	@Override
	public final String toString() {
		return value;
	}
	
	public boolean validateValue() {
		if (validated) return true; // don't want to repeat this action
		setValidated(true); // validation is done only once, either validate (and sanitize) or nullify the value
		if (value != null && value.length() > 0) {
			try {
				LOG.debug("ValidateValue: preparing to validate: " + value);
				doActualValidation();
				LOG.debug("ValidateValue: after validate: " + value);
				return true;
			} catch (Exception e) {
				LOG.debug("ValidateValue: got exception: ", e);
				value = null; // nullify the value, validation failed with exception
				return false;
			}
		}
		return true;
	}

	private void setValidated(boolean validated) {
		this.validated = validated;
	}

	/**
	 * @throws AppSensorException
	 * @throws Exception 
	 */
	public abstract void doActualValidation() throws AppSensorException, Exception;
}
